package com.hn.zhijian.base.data.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.sql.Timestamp;
import java.util.Date;

/**
 * @Author carl chen
 * @date 2018/2/6.
 */
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 字段为空自动填充,如果要使填充生效,一定在在实体类对应的字段上设置fill = FieldFill.INSERT字段！
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 更多查看源码测试用例
        log.info("插入创建时间");
        Object createTime = getFieldValByName("createTime", metaObject);//mybatis-plus版本2.0.9+

        Date timestamp = new Timestamp(System.currentTimeMillis());
        if (createTime == null) {
            setFieldValByName("createTime", timestamp, metaObject);//mybatis-plus版本2.0.9+
            setFieldValByName("updateTime", new Date(System.currentTimeMillis()), metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //更新填充
        log.info("插入更新时间");
        //mybatis-plus版本2.0.9+
        setFieldValByName("updateTime", new Date(System.currentTimeMillis()), metaObject);
    }

}
